import { showWereWolfForm, WereWolfFormOptions } from "@/werewolf/func";
import { WereWolfWitchPhase } from "@/werewolf/phases/witch";
import { WereWolfRole, WereWolfStatus } from "@/werewolf/player";
import { WereWolfNoColor } from "@/werewolf/static";
import { Game, GameComponent } from "@sapi-game/main";

export class WereWolfWitchTool extends GameComponent<WereWolfWitchPhase> {
    get witch() {
        return this.context.players.find(
            (p) => p.role == WereWolfRole.Witch && !p.dead
        );
    }

    override onAttach(): void {
        //毒药
        this.subscribe(
            Game.events.itemUse,
            (t) => {
                if (t.source.id != this.witch?.id) return;
                if (!this.context.poison) {
                    return this.witch.sendMessage("已经没有毒药了");
                }
                this.poisonForm();
            },
            { itemId: "werewolf:poison", players: this.context.players }
        );
        //解药
        this.subscribe(
            Game.events.itemUse,
            (t) => {
                if (!this.context.antidote) {
                    return this.witch?.sendMessage("已经没有解药了");
                }
                const killedPlayer = this.context.players.filter(
                    (p) => p.status == WereWolfStatus.killed
                );
                this.context.antidote = false;
                killedPlayer.forEach((p) => {
                    p.status = WereWolfStatus.Live;
                });
                this.witch?.sendMessage(
                    "§a你成功救了  §e" +
                        killedPlayer.map((p) => p.name).join(",")
                );
                this.state.next();
            },
            { itemId: "werewolf:antidote", players: this.context.players }
        );
    }

    posionFomrData: WereWolfFormOptions = {
        title: "选择毒药使用对象",
        body: "请选择你要毒的人",
        getPlayers: () =>
            this.context.players.filter((p) => p.status == WereWolfStatus.Live),
        onSelect: (player, selected) => {
            if (!this.isAttached) return;
            selected.status = WereWolfStatus.killed;
            selected.poistend = true;
            player.sendMessage(
                `你对[${WereWolfNoColor[selected.no - 1]}${selected.no}号§r]${
                    selected.name
                }用了§5毒药`
            );
            this.context.poison = false;
            this.state.next();
        },
    };

    poisonForm() {
        const witch = this.witch;
        if (!witch?.player) return;
        showWereWolfForm(this.posionFomrData, witch);
    }
}
